package marcoferreira.org.switchonactionbar;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Switch;

/**
 * Created by Marco Ferreira on 20/02/2015.
 */
public class MainActivity extends Activity {

    private boolean shared = false;
    private Switch aSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem item = menu.findItem(R.id.action_share_switch);
        aSwitch = (Switch) item.getActionView();
        aSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shared = aSwitch.isChecked();
                updateIcon(menu.findItem(R.id.action_share_standard));
            }
        });
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_share_standard:
                shared = !shared;
                updateIcon(item);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateIcon(MenuItem item) {
        item.setIcon(shared ? R.drawable.sharing : R.drawable.not_sharing);
        aSwitch.setChecked(shared);
    }
}
